import datetime
import random

from django.db import transaction
from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView
from order import models, orderser

from cart.models import CartModel
from utils.MyRedis import myredis
from utils.authentication import JWTAuthenticationss
from user.models import UserModel

from user.models import UserCoupon

from utils.alipay import AliPaySDK


# 生成一个唯一的订单号
def setno():
    now = datetime.datetime.now().strftime('%Y%m%d-%H%M%S')
    return now + '-' + str(random.randint(1000, 9999))


# 创建视图类
# class SetOrderView(APIView):
#     authentication_classes = [JWTAuthenticationss]
#
#     # 处理创建订单的POST请求
#     @transaction.atomic
#     def post(self, request):
#         user = request.data.get('user')
#         no = myredis.get_str(user)
#         if no:
#             orderno = no
#         else:
#             orderno = setno()
#             myredis.set_str(user, orderno)
#
#         sid = transaction.savepoint()
#         # 尝试执行主要逻辑，如果发生异常则进行回滚处理
#         try:
#             # 从请求数据中获取用户积分、优惠券和支付类型
#             score = request.data.get('score')
#             coupon = request.data.get('coupon')
#             paytype = request.data.get('paytype')
#
#             # 获取用户购物车中所有选中的课程
#             allcourse = CartModel.objects.filter(user=user, selected=True)
#
#             if not allcourse:
#                 return Response({"msg": "购物车内没有商品"})
#
#             # 初始化总价为0，用于累加所有课程的价格
#             totalprice = 0
#             for i in allcourse:
#                 totalprice += i.course.price
#
#             # 将总价转换为浮点数，以便进行后续的计算
#             payprice = float(totalprice)
#
#             # 如果用户提供了积分，并且用户的积分足够，则应用积分优惠
#             if score:
#                 userobj = UserModel.objects.get(id=user)
#                 if userobj.score >= score:
#                     payprice = float(totalprice) - score * 0.1
#                     userobj.score -= score
#                     userobj.save()
#
#             # 如果用户提供了优惠券，则应用优惠券优惠
#             if coupon:
#                 couponobj = UserCoupon.objects.get(id=coupon)
#                 print(couponobj)
#                 payprice = totalprice - couponobj.coupon.price
#                 couponobj.isused = 1
#                 couponobj.save()
#
#             # 构建订单对象，包括订单号、用户、订单总价、支付总价、优惠券和积分
#             orderobj = {"orderno": orderno, "user": user, "orderprice": totalprice, "payprice": payprice,
#                         "coupon": coupon, "score": score}
#
#             # 使用序列化器验证并保存订单数据
#             ordser = orderser.OrderSerializer(data=orderobj)
#             if ordser.is_valid():
#                 ordser.save()
#
#             # 遍历所有课程，构建订单详情并保存
#             for item in allcourse:
#                 detail = {
#                     "order": ordser.data["id"],
#                     "coursename": item.course.name,
#                     "courseprice": item.course.price,
#                     "courseimg": str(item.course.image),
#                     "courseid": item.course.id
#                 }
#                 detailser = orderser.OrderDetailSerializer(data=detail)
#                 if detailser.is_valid():
#                     detailser.save()
#
#             # 删除购物车中的所有选中课程
#             allcourse.delete()
#
#             myredis.set_str(user, orderno)
#
#             # 提交事务
#             transaction.savepoint_commit(sid)
#
#             # 返回成功响应
#             return Response({"msg": "ok", "orderno": orderno, "payprice": payprice})
#         except:
#             # 如果发生异常，回滚事务
#             transaction.savepoint_rollback(sid)
#
#             # 返回失败响应
#             return Response({"msg": "no"})

class SetOrderView(APIView):
    authentication_classes = [JWTAuthenticationss]

    @transaction.atomic
    def post(self, request):
        user = request.data.get("user")
        no = myredis.get_str(user)
        if no:
            orderno = no
        else:
            orderno = setno()
            myredis.set_str(user, orderno)

        sid = transaction.savepoint()
        try:
            score = request.data.get("score")
            coupon = request.data.get("coupon")
            paytype = request.data.get("paytype")
            allcourse = CartModel.objects.filter(user=user, selected=True)
            if not allcourse:
                return Response({"msg": "购物车内没有商品"})
            totalprice = 0
            for i in allcourse:
                totalprice += i.course.price
            payprice = float(totalprice)
            if score:
                userobj = UserModel.objects.get(id=user)
                if userobj.score >= score:
                    payprice = float(totalprice) - score * 0.1
                    userobj.score -= score
                    userobj.save()
            if coupon:
                couponobj = UserCoupon.objects.get(id=coupon)
                payprice = totalprice - couponobj.coupon.price
                couponobj.isused = 1
                couponobj.save()
            orderobj = {"orderno": orderno, "user": user, "orderprice": totalprice, "payprice": payprice,
                        "coupon": coupon, "score": score}
            ordser = orderser.OrderSerializer(data=orderobj)
            if ordser.is_valid():
                ordser.save()
            detail = []
            for i in allcourse:
                detail = {
                    "order": ordser.data["id"],
                    "coursename": i.course.name,
                    "courseprice": i.course.price,
                    "courseimg": str(i.course.image),
                    "courseid": i.course.id
                }
            detailser = orderser.OrderDetailSerializer(data=detail)
            if detailser.is_valid():
                detailser.save()
            allcourse.delete()
            myredis.set_str(user, orderno)
            transaction.savepoint_commit(sid)
            return Response({"msg": "ok", "orderno": orderno, "payprice": payprice})
        except:
            transaction.savepoint_rollback(sid)
            return Response({"msg": "no"})


class TestView(APIView):
    authentication_classes = [JWTAuthenticationss]

    def get(self, request):
        data = request.query_params.dict()
        alipay = AliPaySDK()
        success = alipay.check_sign(data)
        print(success)
        if success:
            orderlist = models.OrderModel.objects.filter(orderno=data["out_trade_no"], status=0).first()
            orderlist.status = 1
            orderlist.payno = data["trade_no"]
            orderlist.paytime = data.get("timestamp")
            orderlist.save()
            if orderlist.score:
                userlist = models.UserModel.objects.get(id=orderlist.user.id)
                userlist.score = userlist.score - orderlist.score
                userlist.save()
            if orderlist.coupon:
                couponlist = models.UserCoupon.objects.get(id=orderlist.coupon)
                couponlist.isused = 1
                couponlist.save()
            myredis.del_str(orderlist.user.id)
            courselist = models.OrderDetailModel.objects.filter(order=orderlist.id)
            ser = orderser.OrderDetailSerializer(courselist, many=True)
            return Response({"msg": "支付成功！",
                             "data": {"time": data.get("timestamp"), "price": data.get("total_amount"),
                                      "course": ser.data}})
        else:
            return Response({"msg": "支付失败！"})


class GetPay(APIView):
    def post(self, request):
        order = request.data.get("order")
        orderlist = models.OrderModel.objects.filter(orderno=order, status=0).first()
        if not orderlist:
            return Response({"msg": "订单不存在"})
        ali = AliPaySDK()
        link = ali.page_pay(order, orderlist.payprice, "慕课网-" + order)
        return Response(link)
